package avicit.bdp.dgs.mdm.service;

import avicit.bdp.common.base.BaseService;
import avicit.bdp.common.utils.BdpLogUtil;
import avicit.bdp.dgs.mdm.dao.ColumnDAO;
import avicit.bdp.dgs.mdm.dto.ColumnDTO;
import avicit.bdp.dgs.mdm.utils.constants.Constants;
import avicit.platform6.api.system.ConvertColumnClient;
import avicit.platform6.api.system.impl.SystemConstant;
import avicit.platform6.commons.utils.BusinessUtil;
import avicit.platform6.commons.utils.ComUtil;
import avicit.platform6.commons.utils.PojoUtil;
import avicit.platform6.core.exception.BusinessException;
import avicit.platform6.core.properties.PlatformConstant;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @金航数码科技有限责任公司
 * @作者：developer
 * @邮箱：developer@avic-digital.com
 * @创建时间： 2023-12-04
 * @类说明：ColumnService
 * @修改记录：
 * @注意事项：
 * @主要功能：字段Service
 */
@Service
public class ColumnService extends BaseService<ColumnDAO, ColumnDTO> {
    private static final Logger logger = LoggerFactory.getLogger(ColumnService.class);

    @Autowired
    private ColumnDAO columnDAO;

    @Autowired
    private CommonService commonService;

    @Autowired
    private ConvertColumnClient convertColumnClient;

    /**
     * 新增字段
     *
     * @param columnDTO
     * @return
     */
    @Transactional
    public String addColumn(ColumnDTO columnDTO) {
        checkAddValidity(columnDTO);

        return saveColumn2Db(columnDTO);
    }

    /**
     * 批量保存字段
     *
     * @param columnList
     * @return
     */
    @Transactional
    public boolean saveColumn(List<ColumnDTO> columnList) {
        if (CollectionUtils.isEmpty(columnList)) {
            return false;
        }

        // 删除所有字段
        deleteColumnInner(null, columnList.get(0).getTableId());
//        this.columnDAO.deleteColumnByCond(null, columnList.get(0).getTableId());

        // 填充数据
        List<ColumnDTO> insertList = new ArrayList<>();
        for (ColumnDTO col : columnList) {
            if (col == null) {
                continue;
            }

            col.setId(ComUtil.getId());
            PojoUtil.setSysProperties(col, PlatformConstant.OpType.insert);

            insertList.add(col);
        }

        // 批量插入字段
        this.columnDAO.batchInsertColumn(insertList);

        return true;
    }

    /**
     * 删除/批量删除字段，多个id使用英文逗号隔开
     *
     * @param id
     * @return
     */
    @Transactional
    public int deleteColumn(String id) {
        if (StringUtils.isBlank(id)) {
            return 0;
        }

        // 删除字段
//        return this.columnDAO.deleteColumnByCond(Arrays.asList(id.trim().split(Constants.COMMA)), null);
        return deleteColumnInner(id, null);
    }

    /**
     * 修改字段
     *
     * @param columnDTO
     * @return
     */
    @Transactional
    public boolean updateColumn(ColumnDTO columnDTO) {
        checkUpdateValidity(columnDTO);

        updateColumn2Db(columnDTO);

        return true;
    }

    /**
     * 查询模型中字段列表
     *
     * @param tableId 模型ID
     * @return
     */
    public List<ColumnDTO> getColumnList(String tableId) {
        if (StringUtils.isEmpty(tableId)) {
            logger.warn("模型ID为空，获取字段列表失败.");
            return new ArrayList<>();
        }

        List<ColumnDTO> queryRet = this.mapper.getColumnListByCond(tableId);
        if (CollectionUtils.isEmpty(queryRet)) {
            logger.warn("未找到字段信息，tableId:" + tableId);
            return new ArrayList<>();
        }

        valueConvert(queryRet);

        return queryRet;
    }

    /**
     * 新增字段合法性检查
     *
     * @param columnDTO
     */
    private void checkAddValidity(ColumnDTO columnDTO) {
        if (columnDTO == null) {
            throw new BusinessException("入参为null");
        }

        if (StringUtils.isEmpty(columnDTO.getName())) {
            throw new BusinessException("名称为空");
        }

        if (StringUtils.isEmpty(columnDTO.getColumnType())) {
            throw new BusinessException("类型为空");
        }
    }

    /**
     * 新增字段合法性检查
     *
     * @param columnDTO
     */
    private void checkUpdateValidity(ColumnDTO columnDTO) {
        if (columnDTO == null) {
            throw new BusinessException("入参为null");
        }

        if (StringUtils.isEmpty(columnDTO.getId())) {
            throw new BusinessException("主键为空");
        }
    }

    /**
     * 持久化到Db
     *
     * @param columnDTO
     * @return
     */
    private String saveColumn2Db(ColumnDTO columnDTO) {
        if (columnDTO == null) {
            return null;
        }

        columnDTO.setId(ComUtil.getId());
        this.insert(columnDTO);

        BdpLogUtil.log4Insert(columnDTO);

        return columnDTO.getId();
    }

    /**
     * 字段持久化到Db
     *
     * @param columnDTO
     * @return
     */
    private String updateColumn2Db(ColumnDTO columnDTO) {
        if (columnDTO == null) {
            return null;
        }

        ColumnDTO oldDTO = this.columnDAO.selectByPrimaryKey(columnDTO.getId());
        if (oldDTO == null) {
            throw new BusinessException("未找到字段，id：" + columnDTO.getId());
        }

        this.updateByPrimaryKeySelective(columnDTO);

        BdpLogUtil.log4Update(columnDTO, oldDTO);

        return columnDTO.getId();
    }

    /**
     * 删除字段信息，并一并删除编码规则
     *
     * @param columnId
     * @param tableId
     * @return
     */
    private int deleteColumnInner(String columnId, String tableId) {
        if (StringUtils.isNotEmpty(columnId)) {
            List<String> idList = Arrays.asList(columnId.trim().split(Constants.COMMA));
            if (CollectionUtils.isNotEmpty(idList)) {
                // 删除字段编码
                for (String id : idList) {
                    this.commonService.deleteCodeByCond(id, null);
                }

                // 删除字段
                this.columnDAO.deleteColumnByCond(idList, null);
            }
        }

        if (StringUtils.isNotEmpty(tableId)) {
            // 删除字段编码
            this.commonService.deleteCodeByCond(null, tableId);

            // 删除字段
            this.columnDAO.deleteColumnByCond(null, tableId);
        }

        return 0;
    }

    /**
     * 通过平台API将字段值转换为名称，包括通用选择组件、通用代码
     *
     * @param dtoList
     */
    private void valueConvert(List<ColumnDTO> dtoList) {
        if (CollectionUtils.isEmpty(dtoList)) {
            return;
        }

        // 设置创建者名称
        Map<String, Set<String>> convertFormData = new HashMap<>();
        for (ColumnDTO dto : dtoList) {
            BusinessUtil.createConvertSet(convertFormData, SystemConstant.USER, dto.getCreatedBy());
        }
        if (convertFormData.size() > 0) {
            //获取请求结果
            Map<String, Map<String, String>> convertResultData = convertColumnClient.replace(convertFormData);
            //循环设置Alias或Name的值
            for (ColumnDTO dto : dtoList) {
                dto.setUserName(BusinessUtil.convertFormat(convertResultData, SystemConstant.USER, dto.getCreatedBy()));
            }
        }
    }
}
